package com.hulk.dryad.manage.framework.mdc.wrapper;


import com.hulk.dryad.common.util.wrapper.CallableWrapper;
import com.hulk.dryad.common.util.wrapper.RunnableWrapper;
import com.hulk.dryad.manage.framework.mdc.constant.MdcConstants;
import com.hulk.dryad.manage.framework.mdc.util.TraceIdUtil;
import org.slf4j.MDC;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.concurrent.ListenableFuture;

import java.util.concurrent.*;

/**
 * @author hulk
 * @version 1.0
 * @date 2021/1/14 13:25
 */

public class ThreadPoolTaskExecutorMdcWrapper extends ThreadPoolTaskExecutor {

	@Override
	public void execute(Runnable task) {
		setMdcIdIfAbsent();
		//Runnable ttlRunnable = TtlRunnable.get(task);
		super.execute(new RunnableWrapper(task));
	}
	@Override
	public void execute(Runnable task, long startTimeout) {
		setMdcIdIfAbsent();
		//Runnable ttlRunnable = TtlRunnable.get(task);
		super.execute(new RunnableWrapper(task),startTimeout);
	}
	@Override
	public Future<?> submit(Runnable task) {
		setMdcIdIfAbsent();
		//Runnable ttlRunnable = TtlRunnable.get(task);
		return super.submit(new RunnableWrapper(task));
	}
	@Override
	public <T> Future<T> submit(Callable<T> task) {
	      setMdcIdIfAbsent();
		  //Callable ttlCallable = TtlCallable.get(task);
		  return super.submit(new CallableWrapper(task));
	}
	@Override
	public ListenableFuture<?> submitListenable(Runnable task) {
		 setMdcIdIfAbsent();
		 //Runnable ttlRunnable = TtlRunnable.get(task);
		 return super.submitListenable(new RunnableWrapper(task));
	}
	@Override
	public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
		setMdcIdIfAbsent();
		//Callable ttlCallable = TtlCallable.get(task);
		return super.submitListenable(new CallableWrapper(task));
	}
	private   void setMdcIdIfAbsent() {
		if (MDC.get(MdcConstants.TRACE_ID) == null) {
			MDC.put(MdcConstants.TRACE_ID, TraceIdUtil.getTraceId());
		}

	}
//	@Override
////	protected BlockingQueue<Runnable> createQueue(int queueCapacity) {
////		return queueCapacity > 0 ? new ArrayBlockingQueue(queueCapacity) : new SynchronousQueue();
////	}

}
